package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.qo.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import cn.wolfcode.car.common.web.AjaxResult;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.SystemPropertyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.beans.DefaultPersistenceDelegate;
import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public AjaxResult upload(MultipartFile file) {
        if (file != null && file.getSize() != 0) {
            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            if ("bpmn".equals(extension)) {
                String upload = null;
                try {
                    upload = FileUploadUtils.upload(SystemConfig.getProfile(), file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return AjaxResult.success("合格", upload);
            } else {
                return AjaxResult.error("上传格式错误");
            }
        } else {
            return AjaxResult.error("不能上传空文件");
        }
    }

    @Override
    public void deploy(String path, String bpmnType, String info) {
        //获取输入流
        File file = new File(SystemConfig.getProfile(), path);
        try {
            //获取到文件
            FileInputStream fileInputStream = new FileInputStream(file);

            //部署流程
            Deployment deploy = repositoryService.createDeployment()
                    .addInputStream(path, fileInputStream)
                    .deploy();

            //获取到流程定义
            ProcessDefinition processDefinition = repositoryService
                    .createProcessDefinitionQuery()
                    .deploymentId(deploy.getId())//通过流程部署的id拿到流程定义
                    .singleResult();

            //释放资源
            fileInputStream.close();

            //插入表
            BpmnInfo bpmnInfo = new BpmnInfo();
            bpmnInfo.setDeploymentId(deploy.getId());//流程部署id
            bpmnInfo.setDeployTime(deploy.getDeploymentTime());//流程部署时间

            bpmnInfo.setInfo(info);//描述信息
            bpmnInfo.setBpmnType(bpmnType);//类型

            bpmnInfo.setBpmnName(processDefinition.getName());//流程图名称
            bpmnInfo.setActProcessId(processDefinition.getId());//流程定义的id
            bpmnInfo.setActProcessKey(processDefinition.getKey());//流程定义的key

            bpmnInfoMapper.insert(bpmnInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public InputStream readResource(String readResource, String type) {
        InputStream resourceAsStream = null;
        //同过流程部署id获取到流程定义
            ProcessDefinition processDefinition = repositoryService
                    .createProcessDefinitionQuery()
                    .deploymentId(readResource)
                    .singleResult();
            //通过传过来的数据来判断是那一个类型
        if ("xml".equals(type)) {
             resourceAsStream = repositoryService
                     .getResourceAsStream(readResource, processDefinition.getResourceName());
        }else if ("png".equals(type)){
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            DefaultProcessDiagramGenerator gen = new DefaultProcessDiagramGenerator();
            resourceAsStream = gen.generateDiagram(bpmnModel, Collections.EMPTY_LIST
                    , Collections.EMPTY_LIST,
                    "宋体", "宋体", "宋体");
        }
        return resourceAsStream;
    }

    @Override
    public void delete(Long id) {
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        //删除bpmnInfo表
        bpmnInfoMapper.deleteByPrimaryKey(id);
        //删除其他的表
        //根据流程部署来获取流程定义
        ProcessDefinition processDefinition = repositoryService.
                createProcessDefinitionQuery().
                deploymentId(bpmnInfo.getDeploymentId()).
                singleResult();

        //删除掉部署文件
        File file = new File(SystemConfig.getProfile(),processDefinition.getResourceName());

        file.delete();
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);

    }

    @Override
    public BpmnInfo queryByType(String carPackage) {

        return bpmnInfoMapper.queryByType(carPackage);
    }

}
